home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1997 April: Mac OS SDK / Dev.CD Apr 97 SDK1.toast / Development Kits (Disc 1) / Apple Shared Library Manager / ASLM Examples / Sample Apps / CPlusSample / Sources / Sample.cp next >
Encoding:
Text File  |  1996-11-19  |  26.6 KB  |  803 lines  |  [TEXT/MPS ]

  1. /*
  2.     File:        Sample.cp
  3.  
  4.     Contains:    This is a simple application, based on the DTS traffic light example,
  5.                 that demonstrates how to use the Shared Library Manager. It puts the
  6.                 functionality of the traffic light window into a shared library and
  7.                 then uses that library from the client application.
  8.  
  9.     Copyright:    © 1993-1994 by Apple Computer, Inc., all rights reserved.
  10.  
  11. */
  12.  
  13. #include <GlobalNew.h>
  14. #include <LibraryManager.h>
  15. #include <LibraryManagerClasses.h>
  16. #include <LibraryManagerUtilities.h>
  17.  
  18. #include <limits.h>
  19. #include <Types.h>
  20. #include <Resources.h>
  21. #include <QuickDraw.h>
  22. #include <Fonts.h>
  23. #include <Events.h>
  24. #include <Windows.h>
  25. #include <Menus.h>
  26. #include <TextEdit.h>
  27. #include <Dialogs.h>
  28. #include <Desk.h>
  29. #include <ToolUtils.h>
  30. #include <Memory.h>
  31. #include <SegLoad.h>
  32. #include <Files.h>
  33. #include <OSUtils.h>
  34. #include <OSEvents.h>
  35. #include <DiskInit.h>
  36. #include <Packages.h>
  37. #include <Traps.h>
  38.  
  39. #include "Sample.h"
  40. #include "SampleLibrary.h"
  41.  
  42. // The "g" prefix is used to emphasize that a variable is global. 
  43.  
  44. // gMac is used to hold the result of a SysEnvirons call. This makes
  45. // it convenient for any routine to check the environment. 
  46.  
  47. SysEnvRec    gMac;                // set up by Initialize 
  48.  
  49. // gHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  50. // trap is available. If it is false, we know that we must call GetNextEvent. 
  51.  
  52. Boolean        gHasWaitNextEvent;    // set up by Initialize 
  53.  
  54. // gInBackground is maintained by our osEvent handling routines. Any part of
  55. // the program can check it to find out if it is currently in the background. 
  56.  
  57. Boolean        gInBackground;        // maintained by Initialize and DoEvent 
  58.  
  59.  
  60. // gTrafficLight is a pointer to our traffic light object. 
  61.  
  62. TTrafficLight    *gTrafficLight = nil;
  63.  
  64. // Here are declarations for all of the C routines. In MPW 3.0 and later we can use
  65. // actual prototypes for parameter type checking. 
  66.  
  67. void EventLoop( void );
  68. void DoEvent( EventRecord *event );
  69. void AdjustCursor( Point mouse, RgnHandle region );
  70. void GetGlobalMouse( Point *mouse );
  71. void DoUpdate( WindowPtr window );
  72. void DoActivate( WindowPtr window, Boolean becomingActive );
  73. void DoContentClick();
  74. void DrawWindow();
  75. void AdjustMenus( void );
  76. void DoMenuCommand( long menuResult );
  77. Boolean DoCloseWindow( WindowPtr window );
  78. void Terminate( void );
  79. void UnLoadTrafficLightLibrary();
  80. void LoadTrafficLightLibrary();
  81. void Initialize( void );
  82. void ForceEnvirons( void );
  83. Boolean IsAppWindow( WindowPtr window );
  84. Boolean IsDAWindow( WindowPtr window );
  85. Boolean TrapAvailable( short tNumber, TrapType tType );
  86. void AlertUser( void );
  87.  
  88. // Define TopLeft and BotRight macros for convenience. Notice the implicit
  89. // dependency on the ordering of fields within a Rect 
  90.  
  91. #define TopLeft(aRect)    (* (Point *) &(aRect).top)
  92. #define BotRight(aRect)    (* (Point *) &(aRect).bottom)
  93.  
  94.  
  95. /*————————————————————————————————————————————————————————————————————————————————————
  96.     _DataInit
  97.  
  98.     This routine is part of the MPW runtime library. This external reference to 
  99.     it is done so that we can unload its segment, %A5Init.
  100.  
  101. ————————————————————————————————————————————————————————————————————————————————————*/
  102.  
  103. extern void _DataInit();
  104.  
  105. /*————————————————————————————————————————————————————————————————————————————————————
  106.     main
  107. ————————————————————————————————————————————————————————————————————————————————————*/
  108.  
  109. #pragma segment Main
  110. void main()
  111. {
  112.     //    If you have stack requirements that differ from the default,
  113.     //    then you could use SetApplLimit to increase StackSpace at 
  114.     //    this point, before calling MaxApplZone. 
  115.     MaxApplZone();                    // expand the heap so code segments load at the top 
  116.  
  117.     Initialize();                    // initialize the program 
  118.         
  119.     EventLoop();                    // call the main event loop 
  120. }
  121.  
  122.  
  123. /*————————————————————————————————————————————————————————————————————————————————————
  124.     EventLoop
  125.  
  126.     Get events forever, and handle them by calling DoEvent.
  127.     Get the events by calling WaitNextEvent, if it's available, otherwise
  128.     by calling GetNextEvent. Also call AdjustCursor each time through the loop.
  129.  
  130. ————————————————————————————————————————————————————————————————————————————————————*/
  131.  
  132. #pragma segment Main
  133. void EventLoop()
  134. {
  135.     RgnHandle    cursorRgn;
  136.     Boolean        gotEvent;
  137.     EventRecord    event;
  138.     Point        mouse;
  139.  
  140.     cursorRgn = NewRgn();            // we’ll pass WNE an empty region the 1st time thru 
  141.     do {
  142.         // use WNE if it is available 
  143.         if ( gHasWaitNextEvent ) {
  144.             GetGlobalMouse(&mouse);
  145.             AdjustCursor(mouse, cursorRgn);
  146.             gotEvent = WaitNextEvent(everyEvent, &event, LONG_MAX, cursorRgn);
  147.         }
  148.         else {
  149.             SystemTask();
  150.             gotEvent = GetNextEvent(everyEvent, &event);
  151.         }
  152.         if ( gotEvent ) {
  153.             // make sure we have the right cursor before handling the event 
  154.             AdjustCursor(event.where, cursorRgn);
  155.             DoEvent(&event);
  156.         }
  157.         //    If you are using modeless dialogs that have editText items,
  158.         //    you will want to call IsDialogEvent to give the caret a chance
  159.         //    to blink, even if WNE/GNE returned FALSE. However, check FrontWindow
  160.         //    for a non-NIL value before calling IsDialogEvent. 
  161.     } while ( true );    // loop forever; we quit via ExitToShell 
  162. } /*EventLoop*/
  163.  
  164.  
  165. /*————————————————————————————————————————————————————————————————————————————————————
  166.     DoEvent
  167.  
  168.     Do the right thing for an event. Determine what kind of event it is, and call
  169.     the appropriate routines.
  170.  
  171. ————————————————————————————————————————————————————————————————————————————————————*/
  172.  
  173. #pragma segment Main
  174.  
  175. void DoEvent( EventRecord *event)
  176. {
  177.     short        part;
  178.     WindowPtr    window;
  179.     Boolean        hit;
  180.     char        key;
  181.     Point        aPoint;
  182.     OSErr        err;
  183.     
  184.     switch ( event->what ) {
  185.         case mouseDown:
  186.             part = FindWindow(event->where, &window);
  187.             switch ( part ) {
  188.                 case inMenuBar:                // process a mouse menu command (if any) 
  189.                     AdjustMenus();
  190.                     DoMenuCommand(MenuSelect(event->where));
  191.                     break;
  192.                 case inSysWindow:            // let the system handle the mouseDown 
  193.                     SystemClick(event, window);
  194.                     break;
  195.                 case inContent:
  196.                     if ( window != FrontWindow() ) {
  197.                         SelectWindow(window);
  198.                         //DoEvent(event);    // use this line for "do first click" 
  199.                     } else
  200.                         DoContentClick();
  201.                     break;
  202.                 case inDrag:                // pass screenBits.bounds to get all gDevices 
  203.                     DragWindow(window, event->where, &qd.screenBits.bounds);
  204.                     break;
  205.                 case inGrow:
  206.                     break;
  207.                 case inZoomIn:
  208.                 case inZoomOut:
  209.                     hit = TrackBox(window, event->where, part);
  210.                     if ( hit ) {
  211.                         SetPort(window);    // the window must be the current port... 
  212.                         EraseRect(&window->portRect);    // because of a bug in ZoomWindow 
  213.                         ZoomWindow(window, part, true);    // note that we invalidate and erase... 
  214.                         InvalRect(&window->portRect);    // to make things look better on-screen 
  215.                     }
  216.                     break;
  217.             }
  218.             break;
  219.         case keyDown:
  220.         case autoKey:                        // check for menukey equivalents 
  221.             key = (char)(event->message & charCodeMask);
  222.             if ( event->modifiers & cmdKey )// Command key down 
  223.                 if ( event->what == keyDown ) {
  224.                     AdjustMenus();            // enable/disable/check menu items properly 
  225.                     DoMenuCommand(MenuKey(key));
  226.                 }
  227.             break;
  228.         case activateEvt:
  229.             DoActivate((WindowPtr) event->message, (event->modifiers & activeFlag) != 0);
  230.             break;
  231.         case updateEvt:
  232.             DoUpdate((WindowPtr) event->message);
  233.             break;
  234.         //  It is not a bad idea to at least call DIBadMount in response
  235.         //    to a diskEvt, so that the user can format a floppy. 
  236.         case diskEvt:
  237.             if ( HighWord(event->message) != noErr ) {
  238.                 SetPt(&aPoint, kDILeft, kDITop);
  239.                 err = DIBadMount(aPoint, event->message);
  240.             }
  241.             break;
  242.         case kOSEvent:
  243.         //    must BitAND with 0x0FF to get only low byte 
  244.             switch ((event->message >> 24) & 0x0FF) {        // high byte of message 
  245.                 case kSuspendResumeMessage:        // suspend/resume is also an activate/deactivate 
  246.                     gInBackground = (event->message & kResumeMask) == 0;
  247.                     DoActivate(FrontWindow(), !gInBackground);
  248.                     break;
  249.             }
  250.             break;
  251.     }
  252. } /*DoEvent*/
  253.  
  254.  
  255. /*————————————————————————————————————————————————————————————————————————————————————
  256.     AdjustCursor
  257.  
  258.     Change the cursor's shape, depending on its position. This also calculates the region
  259.     where the current cursor resides (for WaitNextEvent). If the mouse is ever outside of
  260.     that region, an event would be generated, causing this routine to be called,
  261.     allowing us to change the region to the region the mouse is currently in. If
  262.     there is more to the event than just “the mouse moved”, we get called before the
  263.     event is processed to make sure the cursor is the right one. In any (ahem) event,
  264.     this is called again before we     fall back into WNE.
  265.  
  266. ————————————————————————————————————————————————————————————————————————————————————*/
  267.  
  268. #pragma segment Main
  269. void AdjustCursor( Point mouse, RgnHandle region )
  270. {
  271.     WindowPtr    window;
  272.     RgnHandle    arrowRgn;
  273.     RgnHandle    plusRgn;
  274.     Rect        globalPortRect;
  275.  
  276.     window = FrontWindow();    // we only adjust the cursor when we are in front 
  277.     if ( (! gInBackground) && (! IsDAWindow(window)) ) {
  278.         // calculate regions for different cursor shapes 
  279.         arrowRgn = NewRgn();
  280.         plusRgn = NewRgn();
  281.  
  282.         // start with a big, big rectangular region 
  283.         SetRectRgn(arrowRgn, kExtremeNeg, kExtremeNeg, kExtremePos, kExtremePos);
  284.  
  285.         // calculate plusRgn 
  286.         if ( IsAppWindow(window) ) {
  287.             SetPort(window);    // make a global version of the viewRect 
  288.             SetOrigin(-window->portBits.bounds.left, -window->portBits.bounds.top);
  289.             globalPortRect = window->portRect;
  290.             RectRgn(plusRgn, &globalPortRect);
  291.             SectRgn(plusRgn, window->visRgn, plusRgn);
  292.             SetOrigin(0, 0);
  293.         }
  294.  
  295.         // subtract other regions from arrowRgn 
  296.         DiffRgn(arrowRgn, plusRgn, arrowRgn);
  297.  
  298.         // change the cursor and the region parameter 
  299.         if ( PtInRgn(mouse, plusRgn) ) {
  300.             SetCursor(*GetCursor(plusCursor));
  301.             CopyRgn(plusRgn, region);
  302.         } else {
  303.             SetCursor(&qd.arrow);
  304.             CopyRgn(arrowRgn, region);
  305.         }
  306.  
  307.         // get rid of our local regions 
  308.         DisposeRgn(arrowRgn);
  309.         DisposeRgn(plusRgn);
  310.     }
  311. } /*AdjustCursor*/
  312.  
  313. /*————————————————————————————————————————————————————————————————————————————————————
  314.     GetGlobalMouse
  315.  
  316.     Get the global coordinates of the mouse. When you call OSEventAvail
  317.     it will return either a pending event or a null event. In either case,
  318.     the where field of the event record will contain the current position
  319.     of the mouse in global coordinates and the modifiers field will reflect
  320.     the current state of the modifiers. Another way to get the global
  321.     coordinates is to call GetMouse and LocalToGlobal, but that requires
  322.     being sure that thePort is set to a valid port.
  323.  
  324. ————————————————————————————————————————————————————————————————————————————————————*/
  325.  
  326. #pragma segment Main
  327. void GetGlobalMouse(Point    *mouse)
  328. {
  329.     EventRecord    event;
  330.     
  331.     OSEventAvail(kNoEvents, &event);    // we aren't interested in any events
  332.     *mouse = event.where;                // just the mouse position
  333. } /*GetGlobalMouse*/
  334.  
  335.  
  336. /*————————————————————————————————————————————————————————————————————————————————————
  337.     DoUpdate
  338.         
  339.     This is called when an update event is received for a window.
  340.     It calls DrawWindow to draw the contents of an application window.
  341.     As an effeciency measure that does not have to be followed, it
  342.     calls the drawing routine only if the visRgn is non-empty. This
  343.     will handle situations where calculations for drawing or drawing
  344.     itself is very time-consuming.
  345.  
  346. ————————————————————————————————————————————————————————————————————————————————————*/
  347.  
  348. #pragma segment Main
  349. void DoUpdate( WindowPtr window)
  350. {
  351.     if ( IsAppWindow(window) ) {
  352.         BeginUpdate(window);            // this sets up the visRgn
  353.         if ( ! EmptyRgn(window->visRgn) )// draw if updating needs to be done
  354.             DrawWindow();
  355.         EndUpdate(window);
  356.     }
  357. } /*DoUpdate*/
  358.  
  359. /*————————————————————————————————————————————————————————————————————————————————————
  360.     DoActivate
  361.     
  362.     This is called when a window is activated or deactivated.
  363.     In Sample, the Window Manager's handling of activate and
  364.     deactivate events is sufficient. Other applications may have
  365.     TextEdit records, controls, lists, etc., to activate/deactivate. 
  366.  
  367. ————————————————————————————————————————————————————————————————————————————————————*/
  368.  
  369. #pragma segment Main
  370. void DoActivate(WindowPtr window, Boolean becomingActive)
  371. {
  372.     if ( IsAppWindow(window) ) {
  373.         if ( becomingActive )
  374.             ;// do whatever you need to at activation
  375.         else
  376.             ;// do whatever you need to at deactivation
  377.     }
  378. } /*DoActivate*/
  379.  
  380.  
  381. /*————————————————————————————————————————————————————————————————————————————————————
  382.     DoContentClick
  383.  
  384.     This is called when a mouse-down event occurs in the content of a window.
  385.     Other applications might want to call FindControl, TEClick, etc., to
  386.     further process the click.
  387.  
  388. ————————————————————————————————————————————————————————————————————————————————————*/
  389.  
  390. #pragma segment Main
  391.  
  392. void DoContentClick ()
  393.     gTrafficLight->SetLightState( !gTrafficLight->GetLightState() );
  394.     
  395. } /*DoContentClick*/
  396.  
  397.  
  398. /*————————————————————————————————————————————————————————————————————————————————————
  399.     DrawWindow
  400.  
  401.     Draw the contents of the application window. We do some drawing in color, using
  402.       Classic QuickDraw's color capabilities. This will be black and white on old
  403.        machines, but color on color machines. At this point, the window’s visRgn
  404.        is set to allow drawing only where it needs to be done.
  405.  
  406. ————————————————————————————————————————————————————————————————————————————————————*/
  407.  
  408. #pragma segment Main
  409.  
  410. void DrawWindow()
  411. {    
  412.     gTrafficLight->DrawLight();
  413.  
  414. } /*DrawWindow*/
  415.  
  416.  
  417. /*————————————————————————————————————————————————————————————————————————————————————
  418.     AdjustMenus
  419.     
  420.     Enable and disable menus based on the current state.
  421.     The user can only select enabled menu items. We set up all the menu items
  422.     before calling MenuSelect or MenuKey, since these are the only times that
  423.     a menu item can be selected. Note that MenuSelect is also the only time
  424.     the user will see menu items. This approach to deciding what enable/
  425.     disable state a menu item has the advantage of concentrating all
  426.     the decision-making in one routine, as opposed to being spread throughout
  427.     the application. Other application designs may take a different approach
  428.     that is just as valid.
  429.  
  430. ————————————————————————————————————————————————————————————————————————————————————*/
  431.  
  432. #pragma segment Main
  433. void AdjustMenus()
  434. {
  435.     MenuHandle    menu;
  436.  
  437.     WindowPtr window = FrontWindow();
  438.  
  439.     menu = GetMenuHandle(mFile);
  440.     if ( IsDAWindow(window) )            // we can allow desk accessories to be closed from the menu
  441.         EnableItem(menu, iClose);
  442.     else
  443.         DisableItem(menu, iClose);        // but not our traffic light window
  444.  
  445.     menu = GetMenuHandle(mEdit);
  446.     if ( IsDAWindow(window) ) {            // a desk accessory might need the edit menu…
  447.         EnableItem(menu, iUndo);
  448.         EnableItem(menu, iCut);
  449.         EnableItem(menu, iCopy);
  450.         EnableItem(menu, iClear);
  451.         EnableItem(menu, iPaste);
  452.     } else {                            // …but we don’t use it
  453.         DisableItem(menu, iUndo);
  454.         DisableItem(menu, iCut);
  455.         DisableItem(menu, iCopy);
  456.         DisableItem(menu, iClear);
  457.         DisableItem(menu, iPaste);
  458.     }
  459.  
  460.     gTrafficLight->AdjustMenus( IsAppWindow(window) );
  461.  
  462. } /*AdjustMenus*/
  463.  
  464. /*————————————————————————————————————————————————————————————————————————————————————
  465.     DoMenuCommand
  466.     
  467.     This is called when an item is chosen from the menu bar (after calling
  468.     MenuSelect or MenuKey). It performs the right operation for each command.
  469.     It is good to have both the result of MenuSelect and MenuKey go to
  470.     one routine like this to keep everything organized. It checks to see if the 
  471.     menu hit where the Apple, File, or Edit if so it calls the local DoMenuCommand
  472.     else it must be our traffic light's menu, therefore traffic light menu command 
  473.     is being called.
  474.  
  475. ————————————————————————————————————————————————————————————————————————————————————*/
  476.  
  477. #pragma segment Main
  478. void DoMenuCommand(long menuResult)
  479. {
  480.     short        menuID;                    // the resource ID of the selected menu
  481.     short        menuItem;                // the item number of the selected menu
  482.     short        itemHit;
  483.     Str255        daName;
  484.     short        daRefNum;
  485.     Boolean        handledByDA;
  486.     
  487.     menuID = HighWord(menuResult);        // use macros for efficiency to...
  488.     menuItem = LowWord(menuResult);        // get menu item number and menu number
  489.     switch ( menuID ) {
  490.         case mApple:
  491.             switch ( menuItem ) {
  492.                 case iAbout:            // bring up alert for About
  493.                     itemHit = Alert(rAboutAlert, nil);
  494.                     break;
  495.                 default:                // all non-About items in this menu are DAs
  496.                     // type Str255 is an array in MPW 3 
  497.                     GetMenuItemText(GetMenuHandle(mApple), menuItem, daName);
  498.                     daRefNum = OpenDeskAcc(daName);
  499.                     break;
  500.             }
  501.             break;
  502.         case mFile:
  503.             switch ( menuItem ) {
  504.                 case iClose:
  505.                     DoCloseWindow(FrontWindow());
  506.                     break;
  507.                 case iQuit:
  508.                     Terminate();
  509.                     break;
  510.             }
  511.             break;
  512.         case mEdit:                        // call SystemEdit for DA editing & MultiFinder
  513.             handledByDA = SystemEdit(menuItem-1);    // since we don’t do any Editing 
  514.             break;
  515.         default:                        // this must be our shared library menu item
  516.             gTrafficLight->DoMenuCommand( menuItem );
  517.             break;
  518.     }
  519.     HiliteMenu(0);                        // unhighlight what MenuSelect (or MenuKey) hilited
  520. } /*DoMenuCommand*/
  521.  
  522. /*————————————————————————————————————————————————————————————————————————————————————
  523.     DoCloseWindow
  524.     
  525.     Close a window. This handles desk accessory and application windows. Note the
  526.     traffic library manager allocated the windowrecord for window, so disposing of
  527.     the WindowRecord should be left upon the traffic light library.
  528.     
  529. ————————————————————————————————————————————————————————————————————————————————————*/
  530.  
  531. #pragma segment Main
  532. Boolean DoCloseWindow(WindowPtr window)
  533. {
  534.     if ( IsDAWindow(window) )
  535.         CloseDeskAcc(((WindowPeek) window)->windowKind);
  536.     else if ( IsAppWindow(window) )
  537.         delete gTrafficLight;            // done with trafficlight, deallocate
  538.  
  539.     return true;
  540. } /*DoCloseWindow*/
  541.  
  542. /*————————————————————————————————————————————————————————————————————————————————————
  543.     Terminate
  544.  
  545.     Cleanup the application and exits. Close all of the windows, and cleanup our 
  546.     library. We replace the ExitToShell by UnLoadTrafficLightLibrary so we get a 
  547.     chance to unload the library and cleanup the library manager.
  548.  
  549. ————————————————————————————————————————————————————————————————————————————————————*/
  550.  
  551. #pragma segment Main
  552. void Terminate()
  553. {
  554.     WindowPtr    aWindow;
  555.     Boolean        closed;
  556.     
  557.     closed = true;
  558.     do {
  559.         aWindow = FrontWindow();        //  get the current front window
  560.         if (aWindow != nil)
  561.             closed = DoCloseWindow(aWindow); // close this window
  562.     }
  563.     while (closed && (aWindow != nil));
  564.  
  565.     if (closed) {
  566.         UnLoadTrafficLightLibrary();    // exit if no cancellation
  567.         ExitToShell();
  568.     }
  569. } /*Terminate*/
  570.  
  571.  
  572. /*————————————————————————————————————————————————————————————————————————————————————
  573.     UnLoadTrafficLightLibrary
  574.     
  575.     unload the traffic light object and free the memory allocated by our library
  576.  
  577. ————————————————————————————————————————————————————————————————————————————————————*/
  578.  
  579. void UnLoadTrafficLightLibrary()
  580. {
  581.  
  582.     CleanupLibraryManager();            // clean up the library manager we are done.
  583.     ExitToShell();                        // Hasta la Vista baby!
  584. } /* UnLoadTrafficLightLibrary */
  585.  
  586. /*————————————————————————————————————————————————————————————————————————————————————
  587.     LoadTrafficLightLibrary
  588.     
  589.     load the traffic light library. This library automatically creates a window and
  590.     attach a traffic menu to our current menu.
  591.  
  592. ————————————————————————————————————————————————————————————————————————————————————*/
  593.  
  594. void LoadTrafficLightLibrary()
  595. {
  596.  
  597.     // always initilize the library manager before any Shared Library calls. This
  598.     // creates a local instance of TLibraryManager for accessing our libraries.
  599.     
  600.     if( InitLibraryManager() == kNoError ) {                    
  601.             
  602.         // allocate an instance of our traffic light. Use the default memory pool.
  603.         // Set the exception handling just in case; If failed to allocate our object,
  604.         // exception is thrown via FailNULL, in which case we alert user and cleanup.
  605.         
  606.         TRY
  607.             gTrafficLight = new TTrafficLight; // allocate space from default pool
  608.             FailNULL( gTrafficLight, ErrorCode(), "Failed to create a TTrafficLight object");
  609.         CATCH_ALL
  610.             AlertUser();                // failed to allocate our object
  611.         ENDTRY
  612.     
  613.         if( ! gTrafficLight->IsValid() )// make sure our object is initialized
  614.             AlertUser();
  615.  
  616.     }
  617.     else
  618.         AlertUser();                    // not good. SLM IS NOT INSLALLED.
  619.     
  620. } /* LoadTrafficLightLibrary */
  621.  
  622. /*————————————————————————————————————————————————————————————————————————————————————
  623.     Initialize
  624.     
  625.     Set up the whole world, including global variables, Toolbox managers,
  626.     and menus. Sample is going to create its window, and traffic menu through its
  627.     traffic library, using the shared library manager(Nahhhh...). The Library auto-
  628.     matically create a window, attach a menu and draws the traffic light.
  629.  
  630. ————————————————————————————————————————————————————————————————————————————————————*/
  631.  
  632. #pragma segment Initialize
  633. void Initialize()
  634. {
  635.     Handle        menuBar;
  636.     long        total, contig;
  637.     EventRecord event;
  638.     short        count;
  639.  
  640.     gInBackground = false;
  641.     
  642.     InitGraf((Ptr) &qd.thePort);
  643.     InitFonts();
  644.     InitWindows();
  645.     InitMenus();
  646.     TEInit();
  647.     InitDialogs(nil);
  648.     InitCursor();
  649.     
  650.     // This next bit of code is necessary to allow the default button of our
  651.     // alert be outlined
  652.     
  653.     for (count = 1; count <= 3; count++)
  654.         EventAvail(everyEvent, &event);
  655.          
  656.     // Ignore the error returned from SysEnvirons; even if an error occurred,
  657.     // the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  658.     // call to SysEnvirons by calling it after initializing AppleTalk
  659.  
  660.     SysEnvirons(kSysEnvironsVersion, &gMac);
  661.     
  662.     // Make sure that the machine has at least 128K ROMs. If it doesn't, exit. //
  663.     
  664.     if (gMac.machineType < 0) AlertUser();
  665.             
  666.     // Move TrapAvailable call to after SysEnvirons so that we can tell
  667.     // in TrapAvailable if a tool trap value is out of range.
  668.  
  669.     gHasWaitNextEvent = TrapAvailable(_WaitNextEvent, ToolTrap);
  670.           
  671.     // We used to make a check for memory at this point by examining ApplLimit,
  672.     // ApplicationZone, and StackSpace and comparing that to the minimum size we told
  673.     // MultiFinder we needed. This did not work well because it assumed too much about
  674.     // the relationship between what we asked MultiFinder for and what we would actually
  675.     // get back, as well as how to measure it. Instead, we will use an alternate
  676.     // method comprised of two steps.
  677.  
  678.     // It is better to first check the size of the application heap against a value
  679.     // that you have determined is the smallest heap the application can reasonably
  680.     // work in. This number should be derived by examining the size of the heap that
  681.     // is actually provided by MultiFinder when the minimum size requested is used.
  682.     // The derivation of the minimum size requested from MultiFinder is described
  683.     // in Sample.h. The check should be made because the preferred size can end up
  684.     // being set smaller than the minimum size by the user. This extra check acts to
  685.     // insure that your application is starting from a solid memory foundation. 
  686.  
  687.     if ((long) GetApplLimit() - (long) ApplicationZone() < kMinHeap) AlertUser();
  688.         
  689.     // Next, make sure that enough memory is free for your application to run. It
  690.     // is possible for a situation to arise where the heap may have been of required
  691.     // size, but a large scrap was loaded which left too little memory. To check for
  692.     // this, call PurgeSpace and compare the result with a value that you have determined
  693.     // is the minimum amount of free memory your application needs at initialization.
  694.     // This number can be derived several different ways. One way that is fairly
  695.     // straightforward is to run the application in the minimum size configuration
  696.     // as described previously. Call PurgeSpace at initialization and examine the value
  697.     // returned. However, you should make sure that this result is not being modified
  698.     // by the scrap's presence. You can do that by calling ZeroScrap before calling
  699.     // PurgeSpace. Make sure to remove that call before shipping, though.
  700.  
  701.     PurgeSpace(&total, &contig);
  702.     if (total < kMinSpace) AlertUser();
  703.  
  704.     menuBar = GetNewMBar(rMenuBar);            // read menus into menu bar
  705.     if ( menuBar == nil ) AlertUser();
  706.     SetMenuBar(menuBar);                    // install menus
  707.     DisposeHandle(menuBar);
  708.     AppendResMenu(GetMenuHandle(mApple), 'DRVR');    // add DA names to Apple menu
  709.  
  710.     DrawMenuBar();                            // go ahead and update the menu bar
  711.  
  712.     LoadTrafficLightLibrary();                // Load trafficlight shared library 
  713.     
  714. } /*Initialize*/
  715.  
  716. /*————————————————————————————————————————————————————————————————————————————————————
  717.     IsAppWindow
  718.     
  719.     Check to see if a window belongs to the application. If the window pointer
  720.     passed was NIL, then it could not be an application window. WindowKinds
  721.     that are negative belong to the system and windowKinds less than userKind
  722.     are reserved by Apple except for windowKinds equal to dialogKind, which
  723.     mean it is a dialog.
  724.  
  725. ————————————————————————————————————————————————————————————————————————————————————*/
  726.  
  727. #pragma segment Main
  728. Boolean IsAppWindow( WindowPtr window)
  729. {
  730.     short        windowKind;
  731.  
  732.     if ( window == nil )
  733.         return false;
  734.     else {    // application windows have windowKinds = userKind (8) 
  735.         windowKind = ((WindowPeek) window)->windowKind;
  736.         return ( windowKind == userKind );
  737.     }
  738. } /*IsAppWindow*/
  739.  
  740. /*————————————————————————————————————————————————————————————————————————————————————
  741.     IsDAWindow
  742.  
  743.     Check to see if a window belongs to a desk accessory
  744.  
  745. ————————————————————————————————————————————————————————————————————————————————————*/
  746.  
  747. #pragma segment Main
  748. Boolean IsDAWindow(WindowPtr window)
  749. {
  750.     if ( window == nil )
  751.         return false;
  752.     else    // DA windows have negative windowKinds 
  753.         return ( ((WindowPeek) window)->windowKind < 0 );
  754. } /*IsDAWindow*/
  755.  
  756.  
  757. /*————————————————————————————————————————————————————————————————————————————————————
  758.     TrapAvailable
  759.  
  760.     Check to see if a given trap is implemented. This is only used by the
  761.     Initialize routine in this program, so we put it in the Initialize segment.
  762.     The recommended approach to see if a trap is implemented is to see if
  763.     the address of the trap routine is the same as the address of the
  764.     Unimplemented trap.
  765.  
  766. ————————————————————————————————————————————————————————————————————————————————————*/
  767.  
  768. #pragma segment Initialize
  769. Boolean TrapAvailable( short tNumber, TrapType tType)
  770. {
  771.     if ( ( tType == ToolTrap ) &&
  772.         ( gMac.machineType > envMachUnknown ) &&
  773.         ( gMac.machineType < envMacII ) ) {        // it's a 512KE, Plus, or SE 
  774.         tNumber = tNumber & 0x03FF;
  775.         if ( tNumber > 0x01FF )                    // which means the tool traps 
  776.             tNumber = _Unimplemented;            // only go to 0x01FF 
  777.     }
  778.     return NGetTrapAddress(tNumber, tType) != NGetTrapAddress(_Unimplemented, tType);
  779. } /*TrapAvailable*/
  780.  
  781. /*————————————————————————————————————————————————————————————————————————————————————
  782.     AlertUser
  783.     
  784.     Display an alert that tells the user an error occurred, then exit the program.
  785.     This routine is used as an ultimate bail-out for serious errors that prohibit
  786.     the continuation of the application. Errors that do not require the termination
  787.     of the application should be handled in a different manner. Error checking and
  788.     reporting has a place even in the simplest application. The error number is used
  789.     to index an 'STR#' resource so that a relevant message can be displayed.
  790.  
  791. ————————————————————————————————————————————————————————————————————————————————————*/
  792.  
  793. #pragma segment Main
  794. void AlertUser()
  795. {
  796.     short        itemHit;
  797.  
  798.     SetCursor(&qd.arrow);
  799.     itemHit = Alert(rUserAlert, nil);
  800.     UnLoadTrafficLightLibrary();
  801.     ExitToShell();
  802. } /* AlertUser */